package com.ukefu.webim.util.log;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.webim.util.RLogWarningUtils;
import com.ukefu.webim.web.model.Log;
import com.ukefu.webim.web.model.ReqlogWarningAction;
import com.ukefu.webim.web.model.ReqlogWarningContent;
import com.ukefu.webim.web.model.ReqlogWarningMsg;
import com.ukefu.webim.web.model.SysDic;
import com.ukefu.webim.web.model.SystemConfig;
import com.ukefu.webim.web.model.Template;
import com.ukefu.webim.web.model.UKeFuDic;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxyUtil;

public class UKeFuAppender extends ch.qos.logback.core.ConsoleAppender<ILoggingEvent> {
	@Override
	public void append(ILoggingEvent event) {
		super.append(event);
		try {
			if(UKDataContext.getContext()!=null) {
				Log log = new Log(UKDataContext.SYSTEM_ORGI , null , event.getFormattedMessage() , event.getLevel().toString() , event.getThreadName());
				log.setClazz(event.getLoggerName()) ;
				if(event.getFormattedMessage()!=null && event.getFormattedMessage().length() < 255){
					log.setMemo(event.getFormattedMessage());
				}else{
					log.setMemo(event.getFormattedMessage().substring(0 ,255));
				}
				if(event.getThrowableProxy()!=null){
					log.setMsg(ThrowableProxyUtil.asString(event.getThrowableProxy()));
				}
				
				log.setMethod(event.getThreadName());
				log.setLogtype(event.getLevel().toString().equals(Level.ERROR.toString()) ? "1" : "0") ;
				log.setLogtime(String.valueOf(UKTools.dateFormate.format(new Date()))) ;
				/**
				 * 临时缓存
				 */
				UKDataContext.tempLogQueue.add(log) ;
				
				if (log.getLogtype().equals("1")) {
					SystemConfig systemConfig = UKTools.getSystemConfig();
					if (systemConfig!=null && systemConfig.isEnablereqlogwarning()) {
						List<SysDic> sysDicList =  UKeFuDic.getInstance().getSysDic(UKDataContext.UKEFU_SYSTEM_REQLOG_WARNLV) ;
						SysDic logerrorDic = null ;
						if (sysDicList != null && sysDicList.size() > 0) {
							for(SysDic dic:sysDicList) {
								if (dic.getCode().equals("logerror")) {
									logerrorDic = dic ;
								}
							}
						}
						if (logerrorDic != null) {
							List<ReqlogWarningAction> reqlogWarningActionList = systemConfig.getReqlogWarningAction();
							if (reqlogWarningActionList!= null && reqlogWarningActionList.size()> 0) {
								for(ReqlogWarningAction reqlogWarningAction : reqlogWarningActionList) {
									if (reqlogWarningAction.getWarnid().equals(logerrorDic.getId())) {
										//进行预警
										
										//预警信息
										ReqlogWarningMsg msg = new ReqlogWarningMsg();
										List<ReqlogWarningContent> reqlogWarningContentList = new ArrayList<ReqlogWarningContent>();
										ReqlogWarningContent content = new ReqlogWarningContent();
										content.setWarn(logerrorDic.getName());
				        				msg.setWarnDate(new Date());
				        				msg.setIp(log.getId());
				        				msg.setUsername(log.getUsername());
				        				msg.setUserid(log.getUserid());
										
				        				//拦截动作
										if (!StringUtils.isBlank(reqlogWarningAction.getActionid())) {
											String[] actions = reqlogWarningAction.getActionid().split(",");
											if (actions != null && actions.length > 0) {
												for(int i=0;i<actions.length;i++) {
													if (!StringUtils.isBlank(actions[i])) {
														SysDic actionDic = UKeFuDic.getInstance().getDicItem(actions[i]);
														content.setAction(i!=0?content.getAction()+","+actionDic.getName():actionDic.getName());
													}
												}
											}
										}
				        				
										if (!StringUtils.isBlank(content.getWarn())) {
											reqlogWarningContentList.add(content) ;
										}
										msg.setContent(reqlogWarningContentList);//预警内容
										
										//预警对象
										List<String> useremailList = new ArrayList<String>();
				        				List<String> usermobileList = new ArrayList<String>();
				        				RLogWarningUtils.getTouser(systemConfig.getReqlogwarningtouser(), useremailList, usermobileList);
				        				
										//邮件
										if (!StringUtils.isBlank(systemConfig.getReqlogwarningemailid()) && !StringUtils.isBlank(systemConfig.getReqlogwarningemailtp()) && useremailList.size() > 0) {
					        				Template template = UKTools.getTemplate(systemConfig.getReqlogwarningemailtp()) ;
					    					if (template!=null) {
					    						Map<String, Object> values = new HashMap<String, Object>();
					    						values.put("msg", msg) ;
//					    						String contents = UKTools.getTemplet(template.getTemplettext(), values) ;
//					    						System.out.println("日志预警-邮件预警");
//					    						UKTools.sendMassMail(useremailList, "请求预警信息", content, systemConfig.getReqlogwarningemailid(), UKDataContext.SYSTEM_ORGI);
					    					}
					        			}
					        			//短信
					        			if (!StringUtils.isBlank(systemConfig.getReqlogwarningsmsid()) && !StringUtils.isBlank(systemConfig.getReqlogwarningsmstp())&& usermobileList.size() > 0) {
					        				Template template = UKTools.getTemplate(systemConfig.getReqlogwarningsmstp()) ;
					    					if (template!=null) {
					    						Map<String, Object> values = new HashMap<String, Object>();
					    						values.put("msg", msg) ;
//					    						String contents = UKTools.getTemplet(template.getTemplettext(), values) ;
//					    						System.out.println("日志预警-短信预警");
//					    						for(String mobile : usermobileList) {
//					    							UKTools.sendSms(mobile, systemConfig.getReqlogwarningsmsid(), content, null) ;
//					    							System.out.println(mobile+":"+content);
//					    						}
					    					}
					        			}
					        			break;
									}
								}
							}
						}
					}
				}
			}
		} catch (Throwable sqle) {
			sqle.printStackTrace();
		}

	}
}
